package org.hshk.message.controller;

import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.apache.log4j.Logger;
import org.hshk.message.entity.CpMsgMemberSign;
import org.hshk.message.entity.CpMsgPayDetail;
import org.hshk.message.mapper.CpMsgPayDetailMapper;
import org.hshk.message.outDto.OutMsgApplicationRecord;
import org.hshk.message.repository.CpMsgMemberSignRepository;
import org.hshk.message.repository.CpMsgPayDetailRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GaoChuang on 2017/3/30.
 */
@Api(value = "充值历史 API")
@RestController
@RequestMapping("/payDetails")


//支付详情查询
public class MsgPayDetailQueryController {
    private static final Logger log = Logger.getLogger(MsgPayDetailQueryController.class);

    //支付详情接口
    @Autowired
    CpMsgPayDetailMapper cpMsgPayDetailMapper;
    @Autowired
    CpMsgPayDetailRepository cpMsgPayDetailRepository;
    //短信厂家相关接口
    @Autowired
    CpMsgMemberSignRepository cpMsgMemberSignRepository;

    BeanUtils beanUtils;
    //线程对象保存
    private static final ThreadLocal<Gson> local = new ThreadLocal<Gson>();
    private String string;

    private Gson getGson() {
        if (null == local.get()) {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }

    @ApiOperation(value = "成功充值历史")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "商户id（查询全部时为0）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "brandId", value = "品牌id（查询全部时为0）", required = true, dataType = "int", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "充值记录成功"),
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/getSuccessRechargeHistory", method = RequestMethod.GET, produces = "application/json")

    //充值成功记录 查询
    public String SuccessRechargeHistory(int page, int pageSize, int orgId, int brandId) {
        try {
            log.info("MsgPayDetailQueryController.SuccessRechargeHistory" + "page" + page + "pageSize" + pageSize +
                    "orgId" + orgId + "brandId" + brandId);
            Map<String, Object> paramMsg = new HashMap<String, Object>();
            //sql 时用
            Map<String, Object> paramMsg1 = new HashMap<String, Object>();
            if (0 == page) {
                paramMsg.put("page", "参数错误");
            }
            if (0 == pageSize) {
                paramMsg.put("pageSize", "参数错误");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }
            //计算起始
            //int page1 = page;
            //当前页显示的起始记录数
            //page = (page - 1) * pageSize;

            //计算总条数
            //List<CpMsgPayDetail> totalSize = cpMsgPayDetailMapper.findCount("finished");
            /**
             * Creat by yyl
             * 2017年6月23日09:29:45
             */
            long totalSize = cpMsgPayDetailRepository.countByStatus("finished");

            //List<CpMsgPayDetail> list = new ArrayList<CpMsgPayDetail>();

            if (0 == brandId) {
                //list = cpMsgPayDetailMapper.findByid1Andid2(page1, pageSize, "finished");
                /**
                 * Creat by yyl
                 * 2017年6月23日09:58:14
                 */
                Sort sort = new Sort(Sort.Direction.DESC, "id");
                Pageable pageable = new PageRequest(page - 1, pageSize, sort);
                Page<CpMsgPayDetail> list = cpMsgPayDetailRepository.findByStatus("finished", pageable);

                //创建一个 短信申请记录 的集合
                List<OutMsgApplicationRecord> out = new ArrayList<OutMsgApplicationRecord>();
                for (CpMsgPayDetail cpMsgPayDetail : list.getContent()) {
                    OutMsgApplicationRecord outMsgApplicationRecord = new OutMsgApplicationRecord();
                    beanUtils.copyProperties(cpMsgPayDetail, outMsgApplicationRecord);
                    //查询正在使用的 短信账号(用户商家表)
                    CpMsgMemberSign cpMsgMemberSign = cpMsgMemberSignRepository.findByBrandIdAndOrgIdAndIsUsed(cpMsgPayDetail.getBrandId(), cpMsgPayDetail.getUid(), "Yes");
                    if (null == cpMsgMemberSign) {
                        log.error("MsgPayDetailQueryController.SuccessRechargeHistory" + "cpMsgMemberSign表参数不存在");
                        paramMsg.put("resultCode", "fail");
                        paramMsg.put("resultMsg", "cpMsgMemberSign表参数不存在");
                        return getGson().toJson(paramMsg);
                    }
                    outMsgApplicationRecord.setMsgUsername(cpMsgMemberSign.getMsgUsername());
                    out.add(outMsgApplicationRecord);
                }
                paramMsg.put("totalSize", totalSize);
                paramMsg.put("msgPayDetail", out);
                return getGson().toJson(paramMsg);
            } else {
                paramMsg1.put("id1", page);
                paramMsg1.put("id2", pageSize);
                paramMsg1.put("finished", "finished");
                paramMsg1.put("orgId", orgId);
                paramMsg1.put("brandId", brandId);

                //Integer.valueOf()把String 型转换为Integer对象。
                // int size = Integer.valueOf(cpMsgPayDetailMapper.findByUidAndBrandIdAndStatus(orgId, brandId, "finished").size());//totalSize
                /**
                 * Creat by yyl
                 * 2017年6月23日09:43:41
                 */
                int size = Integer.valueOf(cpMsgPayDetailRepository.findByUidAndBrandIdAndStatus(orgId, brandId, "finished").size());


                List<CpMsgPayDetail> list = cpMsgPayDetailMapper.findByid1Andid3(paramMsg1);
                List<OutMsgApplicationRecord> out = new ArrayList<OutMsgApplicationRecord>();
                for (CpMsgPayDetail cpMsgPayDetail : list) {
                    OutMsgApplicationRecord outMsgApplicationRecord = new OutMsgApplicationRecord();
                    beanUtils.copyProperties(cpMsgPayDetail, outMsgApplicationRecord);
                    CpMsgMemberSign cpMsgMemberSign = cpMsgMemberSignRepository.findByBrandIdAndOrgIdAndIsUsed(cpMsgPayDetail.getBrandId(), cpMsgPayDetail.getUid(), "Yes");
                    if (null == cpMsgMemberSign) {
                        log.error("MsgPayDetailQueryController.SuccessRechargeHistory" + "cpMsgMemberSign表参数不存在");
                        paramMsg.put("resultCode", "fail");
                        paramMsg.put("resultMsg", "cpMsgMemberSign表参数不存在 ");
                        return getGson().toJson(paramMsg);
                    }
                    outMsgApplicationRecord.setMsgUsername(cpMsgMemberSign.getMsgUsername());
                    out.add(outMsgApplicationRecord);
                }
                paramMsg.put("totalSize", size);
                paramMsg.put("msgPayDetail", out);
                return getGson().toJson(paramMsg);
            }

        } catch (Exception ex) {
            log.error("MsgPayDetailQueryController.SuccessRechargeHistory" + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }

    @ApiOperation(value = "申请充值列表分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示", required = true, dataType = "int", paramType = "path"),
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/page/{page}/pageSize/{pageSize}", method = RequestMethod.GET, produces = "application/json")

    //充值申请 分页显示
    public String ApplicationHistory(@PathVariable int page, @PathVariable int pageSize) {
        try {
            log.info("MsgPayDetailQueryController.ApplicationHistory" + "page" + page + "pageSize" + pageSize);
            Map<String, Object> paramMsg = new HashMap<String, Object>();
            if (0 == page) {
                paramMsg.put("page", "参数错误");
            }
            if (0 == pageSize) {
                paramMsg.put("pageSize", "参数错误");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }
            //计算起始
            //int page1 = (page - 1) * pageSize;

            //计算总条数
            //List<CpMsgPayDetail> totalSize = cpMsgPayDetailMapper.findCount("payed");
            /**
             * Creat by yyl
             * 2017年6月23日09:38:15
             */
            long totalSize = cpMsgPayDetailRepository.countByStatus("finished");

            paramMsg.put("totalSize", totalSize);

            //创建 商家支付详情 对象
            //List<CpMsgPayDetail> list = new ArrayList<CpMsgPayDetail>();
            //list = cpMsgPayDetailMapper.findByid1Andid2(page1, pageSize, "payed");
            /**
             * Creat by yyl
             * 2017年6月23日10:17:46
             */
            Sort sort = new Sort(Sort.Direction.DESC, "id");
            Pageable pageable = new PageRequest(page - 1, pageSize, sort);
            Page<CpMsgPayDetail> list = cpMsgPayDetailRepository.findByStatus("payed", pageable);

            List<OutMsgApplicationRecord> out = new ArrayList<OutMsgApplicationRecord>();
            for (CpMsgPayDetail cpMsgPayDetail : list.getContent()) {
                OutMsgApplicationRecord outMsgApplicationRecord = new OutMsgApplicationRecord();
                beanUtils.copyProperties(cpMsgPayDetail, outMsgApplicationRecord);
                //查询短信账号
                CpMsgMemberSign cpMsgMemberSign = cpMsgMemberSignRepository.findByBrandIdAndOrgIdAndIsUsed(cpMsgPayDetail.getBrandId(), cpMsgPayDetail.getUid(), "Yes");
                if (null == cpMsgMemberSign) {
                    log.error("MsgPayDetailQueryController.SuccessRechargeHistory" + "cpMsgMemberSign表参数不存在");
                    paramMsg.put("resultCode", "fail");
                    paramMsg.put("resultMsg", "cpMsgMemberSign表参数不存在  ");
                    return string;
                }
                outMsgApplicationRecord.setMsgUsername(cpMsgMemberSign.getMsgUsername());
                out.add(outMsgApplicationRecord);
            }

            paramMsg.put("msgPayDetail", out);
            return getGson().toJson(paramMsg);

        } catch (Exception ex) {
            //出现异常时
            log.error("MsgPayDetailQueryController.ApplicationHistory" + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }

    }
}
